import React, { useState, useEffect, useMemo } from 'react';

import { SearchOutlined } from '@ant-design/icons';

import type {
  DeviceItemDetail,
  SysUploadDataOldType,
  SysHistoryData,
} from '@/api/deviceManagerApi';
import { deviceManagerHistoryApi } from '@/api/deviceManagerApi';
import { ReadWriteTypeList, getEnumLabel } from '@/constants/common';

const { RangePicker } = ADatePicker;

/**
 * 属性记录组件属性
 */
interface PropertyRecordsProps {
  /** 设备详情 */
  deviceDetail: DeviceItemDetail;
  /** 上报数据 */
  reportData: SysUploadDataOldType | null;
  /** 上报数据加载状态 */
  reportLoading: boolean;
  /** 选中的属性名称 */
  selectedAttributeName?: string;
}

/**
 * 属性记录组件
 */
const PropertyRecords: React.FC<PropertyRecordsProps> = ({
  deviceDetail,
  reportData: _reportData,
  reportLoading: _reportLoading,
  selectedAttributeName: _selectedAttributeName,
}) => {
  const [form] = AForm.useForm();
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState<SysHistoryData[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [currentAttributeName, setCurrentAttributeName] = useState<string>('');

  // 从 metaDataJson 中获取属性列表
  const getPropertyOptions = () => {
    if (!deviceDetail?.metaDataJson) return [];

    try {
      const metaData =
        typeof deviceDetail.metaDataJson === 'string'
          ? JSON.parse(deviceDetail.metaDataJson)
          : deviceDetail.metaDataJson;

      if (metaData && metaData.properties && Array.isArray(metaData.properties)) {
        return metaData.properties.map((prop: any) => ({
          label: `${prop.name}`,
          value: prop.identifier,
          dataType: prop.dataType?.type || 'unknown',
          unit: prop.dataType?.specs?.unit || '',
          accessMode: prop.accessMode || 'r',
        }));
      }
    } catch (error) {
      console.error('解析 metaDataJson 失败:', error);
    }

    return [];
  };

  const propertyOptions = getPropertyOptions();

  // 获取属性记录数据
  const fetchPropertyRecords = async (page = 1, pageSize = 20) => {
    setLoading(true);
    try {
      const formValues = form.getFieldsValue();
      const params: any = {
        page,
        pageSize,
        deviceCode: deviceDetail.code,
        productCode: deviceDetail.productCode,
        type: 1, // 默认type为1（属性）
      };

      // 确保设备编码存在
      if (!deviceDetail.code) {
        console.warn('设备编码为空，无法查询属性记录');
        setRecords([]);
        setPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
        setLoading(false);
        return;
      }

      // 添加属性名称
      if (formValues.attributeName) {
        params.attributeName = formValues.attributeName;
      }

      // 添加时间范围
      if (formValues.dateRange && formValues.dateRange[0] && formValues.dateRange[1]) {
        params.startTime = formValues.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
        params.endTime = formValues.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
      }

      // 调试日志：确认参数
      console.log('属性记录查询参数:', params);

      const res = await deviceManagerHistoryApi(params);

      if (res.success && res.data) {
        const records = res.data.records || [];
        const total = res.data.total || 0;

        setRecords(records);
        setPagination({
          current: page,
          pageSize,
          total,
        });
      } else {
        setRecords([]);
        setPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      }
    } catch (error) {
      console.error('获取属性记录失败:', error);
      window.$message.error('获取属性记录失败');
      setRecords([]);
      setPagination({
        current: 1,
        pageSize: 20,
        total: 0,
      });
    } finally {
      setLoading(false);
    }
  };

  // 搜索处理
  const handleSearch = () => {
    form.validateFields().then(() => {
      fetchPropertyRecords(1, pagination.pageSize);
    });
  };

  // 分页变化处理
  const handleTableChange = (page: number, pageSize: number) => {
    fetchPropertyRecords(page, pageSize);
  };

  // 监听表单值变化，更新当前属性名称
  useEffect(() => {
    const attributeName = form.getFieldValue('attributeName');
    if (attributeName !== currentAttributeName) {
      setCurrentAttributeName(attributeName || '');
    }
  });

  // 初始化数据
  useEffect(() => {
    if (deviceDetail.code && propertyOptions.length > 0) {
      // 只在没有选中属性时设置默认值，避免死循环
      const formAttributeName = form.getFieldValue('attributeName');
      if (!formAttributeName) {
        const defaultValue = propertyOptions[0].value;
        form.setFieldValue('attributeName', defaultValue);
        setCurrentAttributeName(defaultValue);
        // 设置默认值后手动调用一次数据获取
        fetchPropertyRecords();
      } else {
        setCurrentAttributeName(formAttributeName);
      }
    }
  }, [deviceDetail.code, propertyOptions.length]); // 只依赖设备编码和属性数量

  // 单独的初始化数据加载
  useEffect(() => {
    if (deviceDetail.code) {
      fetchPropertyRecords();
    }
  }, [deviceDetail.code]);

  // 表格列定义
  const columns = [
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
    },
    {
      title: '历史属性时间',
      dataIndex: 'time',
      key: 'time',
    },
  ];

  // 获取当前选中属性的信息
  const currentPropertyInfo = useMemo(() => {
    if (!currentAttributeName || propertyOptions.length === 0) {
      return { name: '', dataType: '', unit: '', accessMode: '' };
    }

    const currentProperty = propertyOptions.find(
      (prop: any) => prop.value === currentAttributeName
    );
    return {
      name: currentProperty?.label.split(' (')[0] || '',
      dataType: currentProperty?.dataType || '',
      unit: currentProperty?.unit || '',
      accessMode: currentProperty?.accessMode || 'r',
    };
  }, [currentAttributeName, propertyOptions]);

  // 获取读写模式的显示文本
  const getAccessModeText = (accessMode: string) => {
    return getEnumLabel(ReadWriteTypeList, accessMode, '只读');
  };

  return (
    <div className="p-4">
      {/* 查询条件 */}
      <div className="mb-4">
        <AForm form={form} layout="inline" onFinish={handleSearch}>
          <ARow gutter={8} align="middle" style={{ width: '100%' }}>
            <ACol span={8}>
              <AForm.Item name="attributeName" label="属性名称" style={{ marginBottom: 0 }}>
                <ASelect
                  options={propertyOptions}
                  style={{ width: '100%' }}
                  placeholder="请选择属性名称"
                  onChange={value => {
                    setCurrentAttributeName(value || '');
                  }}
                />
              </AForm.Item>
            </ACol>
            <ACol span={12}>
              <AForm.Item name="dateRange" label="时间范围" style={{ marginBottom: 0 }}>
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder={['开始时间', '结束时间']}
                  style={{ width: '100%' }}
                />
              </AForm.Item>
            </ACol>
            <ACol span={2}>
              <AButton
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                loading={loading}
              >
                搜索
              </AButton>
            </ACol>
          </ARow>
        </AForm>
      </div>

      {/* 属性信息显示 */}
      {form.getFieldValue('attributeName') && currentPropertyInfo.name && (
        <div className="mb-4 p-3 bg-gray-50 rounded">
          <span className="text-sm text-gray-600">
            读写模式:{' '}
            <span className="font-medium text-gray-800">
              {getAccessModeText(currentPropertyInfo.accessMode)}
            </span>
            {currentPropertyInfo.dataType && (
              <>
                {' '}
                数据类型:{' '}
                <span className="font-medium text-gray-800">{currentPropertyInfo.dataType}</span>
              </>
            )}
            {currentPropertyInfo.unit && (
              <>
                {' '}
                标识符:{' '}
                <span className="font-medium text-gray-800">
                  {form.getFieldValue('attributeName')}
                </span>
              </>
            )}
          </span>
        </div>
      )}

      {/* 数据表格 */}
      <ATable
        columns={columns}
        dataSource={records}
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 条记录，当前显示第 ${range[0]}-${range[1]} 条`,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }}
        scroll={{ y: 400 }}
        size="middle"
        locale={{
          emptyText: '暂无数据',
        }}
      />
    </div>
  );
};

export default PropertyRecords;
